<template>
  <div>
    <el-card>
      <div>
        <span>库存调拨记录</span>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="20">
            <el-input
              placeholder="调拨单号"
              v-model="searchModel.transferId"
              style="width: 300px; margin: 10px"
              clearable
            ></el-input>

            <el-select
              v-model="searchModel.outWarehouseId"
              filterable
              placeholder="调出仓库"
              style="margin: 10px"
              clearable
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="searchModel.saveWarehouseId"
              filterable
              placeholder="调入仓库"
              style="margin: 10px"
              clearable
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>

            <el-date-picker
              style="margin: 10px"
              v-model="searchModel.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>

            <el-button
              style="margin: 10px"
              type="primary"
              icon="el-icon-search"
              @click="getTransferTable()"
              >查 询</el-button
            >
          </el-col>
          <el-col :span="4" align="right">
            <el-button
              style="margin: 10px"
              type="primary"
              @click="CreateTransferVisible = true"
              >创建调拨单</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-table
            :data="transferTableNumberList"
            style="width: 100%"
            v-loading="loading"
            border
          >
            <el-table-column label="调拨单号" width="180">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  :title="getTransNumTitle(scope.row)"
                  width="360"
                  trigger="hover"
                >
                  <el-divider></el-divider>
                  <div>
                    <div
                      style="margin: 10px; font-size: 16px"
                      v-for="(value, key) of getProductTransferNum(
                        scope.row.transferId
                      )"
                      :key="key"
                    >
                      {{ value }} <br />
                    </div>
                    <div align="right">
                      共计：{{ addTransNum(scope.row.transferId) }} 台
                    </div>
                  </div>
                  <el-link
                    :underline="false"
                    @click="openTransferInfoUi(scope.row.transferId)"
                    slot="reference"
                    align="left"
                    >{{ scope.row.transferId }}</el-link
                  >
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column
              prop="outWarehouseName"
              label="出库仓库"
              width="180"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="saveWarehouseName"
              label="入库仓库"
              width="180"
              align="center"
            >
            </el-table-column>

            <el-table-column
              prop="createTime"
              label="调拨日期"
              width="180"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="operator"
              label="操作人"
              width="180"
              align="center"
            >
            </el-table-column>

            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="openTransferInfoUi(scope.row.transferId)"
                  >详情</el-button
                >
                <el-button type="text" @click="deleteTransferById(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <!-- 分页组件 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchModel.pageNo"
          :page-sizes="[20, 40, 60, 100]"
          :page-size="searchModel.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-drawer
      title="创建调拨单"
      :visible.sync="CreateTransferVisible"
      direction="rtl"
      size="50%"
      :before-close="handleClose"
      @close="colseTransfer"
    >
      <el-card>
        <el-form
          :model="TransferGoodsForm"
          ref="transferGoodsRef"
          :rules="transferRules"
        >
          <el-form-item label="调出仓库" prop="outWarehouseId">
            <el-select
              v-model="TransferGoodsForm.outWarehouseId"
              placeholder="调出仓库"
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="调入仓库" prop="saveWarehouseId">
            <el-select
              v-model="TransferGoodsForm.saveWarehouseId"
              placeholder="调入仓库"
              clearable
            >
              <el-option
                v-for="item in allwareHouseName"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="TransferGoodsForm.remark"
              style="margin-left: 28px; width: 600px"
              placeholder="备注"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-button
          type="primary"
          size="small"
          @click="OpenAddTransferProducTi()"
          >添加商品</el-button
        >
        <el-drawer
          title="添加调拨商品"
          :append-to-body="true"
          :visible.sync="innerCreateTransferVisible"
          :before-close="handleClose"
          @close="cleaSelectIionListForm"
          size="48%"
        >
          <el-card>
            <el-row>
              <el-col>
                <el-input
                  v-model="productSearchModel.goodsName"
                  placeholder="商品名称"
                  style="width: 180px"
                  size="small"
                  clearable
                ></el-input>
                <el-input
                  v-model="productSearchModel.serialNumber"
                  placeholder="序列号"
                  style="width: 180px; margin-left: 10px"
                  size="small"
                  clearable
                ></el-input>
                <el-button
                  style="margin: 10px"
                  type="primary"
                  size="small"
                  @click="getProductList()"
                  >搜 索</el-button
                >
                <el-button style="margin: 10px" size="small">重 置</el-button>
              </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-table
              :data="productList"
              @selection-change="handleSelectionChange"
              v-loading="productLoading"
              max-height="1000"
              ref="multipleTable"
              :row-key="getRowKeys"
            >
              <el-table-column
                type="selection"
                width="50"
                :reserve-selection="true"
              >
              </el-table-column>
              <el-table-column
                property="goodsName"
                label="商品名称"
              ></el-table-column>

              <el-table-column label="库存">
                <template slot-scope="scope">
                  {{ scope.row.InventoryNum }} 台
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
              @size-change="handleSizeChangeProduct"
              @current-change="handleCurrentChangeProduct"
              :current-page="productSearchModel.pageNo"
              :page-sizes="[10, 20, 40, 60]"
              :page-size="productSearchModel.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productTotal"
            >
            </el-pagination>

            <el-row>
              <el-col align="right">
                <el-button
                  style="margin: 10px"
                  type="primary"
                  size="smell"
                  @click="addProduct"
                  >确 定</el-button
                >
                <el-button
                  style="margin: 10px"
                  size="smell"
                  @click="innerCreateTransferVisible = false"
                  >取 消</el-button
                >
              </el-col>
            </el-row>
          </el-card>
        </el-drawer>

        <el-divider></el-divider>
        <el-table :data="TransferGoodsForm.transferGoodsList" max-height="600">
          <el-table-column
            property="goodsName"
            label="商品名称"
          ></el-table-column>
          <el-table-column label="库存" width="200">
            <template slot-scope="scope">
              {{ scope.row.InventoryNum }} 台
            </template>
          </el-table-column>
          <el-table-column label="调拨数量" width="400">
            <template slot-scope="scope">
              <el-button
                style="width: 200px"
                @click="openAddSerialNumberUi(scope.row)"
                >{{
                  scope.row.transferGoods == null ||
                  scope.row.transferGoods == undefined
                    ? ""
                    : scope.row.transferGoods.length
                }}</el-button
              >
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deleteProduct(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row>
          <el-col align="right">
            <el-button
              style="margin: 10px"
              type="primary"
              @click="TransferGoods"
              >确 定</el-button
            >
            <el-button
              style="margin: 10px"
              @click="CreateTransferVisible = false"
              >取 消</el-button
            >
          </el-col>
        </el-row>
      </el-card>
    </el-drawer>

    <!-- 调拨对话框 -->
    <el-dialog
      title="选择序列号"
      :visible.sync="dialogFormVisible"
      width="626px"
    >
      <el-row>
        <el-col>
          <div>
            <el-transfer
              v-model="TransferGoodsData"
              :data="SerivalData"
              filterable
              :filter-method="filterMethod"
              :titles="['出库仓', '入库仓']"
              filter-placeholder="请输入序列号"
            >
            </el-transfer>
          </div>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col align="right">
          <el-button size="smell" type="primary" @click="saveTransferGoods"
            >确 定</el-button
          >
          <el-button size="smell" @click="colseTransferGoods">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      title="调拨详情"
      :visible.sync="dialogFormVisibleInfo"
      width="600px"
      @close="clearInfoData"
    >
      <el-table :data="transferInfoList" style="width: 100%">
        <el-table-column prop="goodsName" label="商品名称" width="180">
        </el-table-column>
        <el-table-column prop="serialNumber" label="序列号"> </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import warehouseApi from "@/api/inventory/warehouse";
import productApi from "@/api/inventory/product";
import inventoryApi from "@/api/inventory/inventory";
import transferRecordApi from "@/api/inventory/transferRecord";
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      total: 0,
      productTotal: 0,
      Img401: "http://154.8.182.144:9999/sys/common/download?name=401.gif",
      // Img401: "http://www.quzhi.org.cn:9999/sys/common/download?name=401.gif",

      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },

      transferTableNumberList: [],

      // 仓库名称
      allwareHouseName: [],

      // 创建调拨单号
      CreateTransferVisible: false,
      innerCreateTransferVisible: false,

      // 调拨序列号列表

      TransferGoodsForm: {
        transferGoodsList: [],
      },
      // 选中的商品列表
      productSearchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      productList: [],

      // 加载动画
      productLoading: false,

      // 调拨单加载动画
      loading: false,

      // 多选
      multipleSelection: [],

      // 调拨对话框
      dialogFormVisible: false,

      SerivalData: [],
      TransferGoodsData: [],
      transferLoading: false,
      // 临时存储需要调拨的商品信息Id
      tempProductIndex: "",

      transferRules: {
        outWarehouseId: [
          { required: true, message: "请选择调出仓库", trigger: "change" },
        ],
        saveWarehouseId: [
          { required: true, message: "请选择调入仓库", trigger: "change" },
        ],
        remark: [
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur",
          },
        ],
      },
      // 调拨单号对应调拨商品数量
      AllTransferGoodsNum: [],

      // 调拨详情列表
      transferInfoList: [],
      dialogFormVisibleInfo: false,
      transferInfoLoading: false,
    };
  },
  methods: {
    // 确认关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 清理表单数据
    cleaSelectIionListForm() {
      this.multipleSelection = [];
      // 选中的商品列表
      this.productSearchModel = {
        pageNo: 1,
        pageSize: 10,
      };
    },
    clearInfoData() {
      this.transferInfoList = [];

      this.transferInfoLoading = false;
    },

    // 取消库存调拨
    colseProductList() {
      this.$confirm("此操作将清除所有选择的调拨库存, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "取消!",
          });
          // 点击取消则清除选中列表
          this.$refs.multipleTable.clearSelection();
          this.multipleSelection = [];
          // 选中的商品列表
          this.productSearchModel = {
            pageNo: 1,
            pageSize: 10,
          };
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    // 添加商品的库存调拨清单中
    addProduct() {
      // 判断原数据中是否有，没有就添加，有就跳过
      var flag = true;

      var data = [];
      var allSelectId = [];
      var allTransferGoodsID = [];
      for (const select of this.multipleSelection) {
        for (const transferGoods of this.TransferGoodsForm.transferGoodsList) {
          if (transferGoods.id == select.id) {
            flag = false;
            break;
          } else {
            flag = true;
            data = select;
          }
        }
        if (flag) {
          this.TransferGoodsForm.transferGoodsList.push(select);
        }
      }

      for (const select of this.multipleSelection) {
        allSelectId.push(select.id);
      }

      for (const transferGoods of this.TransferGoodsForm.transferGoodsList) {
        allTransferGoodsID.push(transferGoods.id);
      }

      // 删除未勾选的数据
      // 如果显示数据有，但是勾选数据没有，则删除

      if (allSelectId.length < allTransferGoodsID.length) {
        var deleteIds = []; // 存放需要删除的ID

        allTransferGoodsID.forEach((item) => {
          var index = allSelectId.indexOf(item);
          if (index < 0) {
            deleteIds.push(item);
          }
        });
      }

      if (deleteIds != null || deleteIds != undefined) {
        deleteIds.forEach((item) => {
          for (const transferGoods of this.TransferGoodsForm
            .transferGoodsList) {
            if (item === transferGoods.id) {
              this.deleteProduct(transferGoods);
            }
          }
        });
      }
      // 关闭
      this.innerCreateTransferVisible = false;
    },

    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getTransferTable();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getTransferTable();
    },

    handleSizeChangeProduct(pageSize) {
      this.productSearchModel.pageSize = pageSize;
      this.getProductList();
    },
    handleCurrentChangeProduct(pageNo) {
      this.productSearchModel.pageNo = pageNo;
      this.getProductList();
    },

    // 获取所有仓库名称
    getAllwareHouseName() {
      warehouseApi.selseAllName().then((response) => {
        this.allwareHouseName = response.data;
      });
    },

    // 获取调拨清单列表
    getTransferTable() {
      this.loading = true;
      transferRecordApi
        .getGoodsRecordList(this.searchModel)
        .then((response) => {
          this.transferTableNumberList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      // 获取所有仓库名称
      this.getAllwareHouseName();

      // 获取调拨商品数量
      this.getAllTransferGoodsNum();
    },

    // 获取调拨商品数量
    getAllTransferGoodsNum() {
      transferRecordApi
        .getAllTransferGoodsNum(this.searchModel)
        .then((response) => {
          this.AllTransferGoodsNum = response.data;
        });
    },
    // 多选框
    handleSelectionChange(val) {
      this.multipleSelection = val; // 被选中的商品
    },

    // 获取商品列表
    getProductList() {
      // Can740-00331
      // 判断调出仓库是否为空
      this.productLoading = true;
      productApi
        .getProductByWarehouse(this.productSearchModel)
        .then((response) => {
          this.productList = response.data.rows;
          this.productTotal = response.data.total;
          this.productLoading = false;
        });
    },

    // 打开添加调拨库存抽屉
    OpenAddTransferProducTi() {
      this.productSearchModel.warehouseId =
        this.TransferGoodsForm.outWarehouseId;

      if (
        this.productSearchModel.warehouseId == null ||
        this.productSearchModel.warehouseId == undefined ||
        this.productSearchModel.warehouseId === ""
      ) {
        this.$message({
          type: "warning",
          message: "请选择调出仓库",
        });
      } else {
        this.getProductList();
        this.innerCreateTransferVisible = true;
      }
    },

    getRowKeys(row) {
      return row.id;
    },

    // 删除列表中的调拨商品
    deleteProduct(product) {
      let index = this.TransferGoodsForm.transferGoodsList.indexOf(product);

      if (index !== -1) {
        this.TransferGoodsForm.transferGoodsList.splice(index, 1);
        // 取消勾选
        this.$refs.multipleTable.toggleRowSelection(product, false);

        // if(this.$refs.multipleTable != null || this.$refs.multipleSelection != undefined){
        //   this.$refs.multipleSelection.toggleRowSelection(product, false)
        // }
      }
    },

    // 打开调拨序列号对话框
    openAddSerialNumberUi(product) {
      // 获取所有商品对应的序列号
      let inventory = {
        warehouseId: this.TransferGoodsForm.outWarehouseId,
        productId: product.id,
      };

      // 获取当前商品索引
      this.tempProductIndex =
        this.TransferGoodsForm.transferGoodsList.indexOf(product);

      inventoryApi.getWarehouseInventory(inventory).then((response) => {
        this.SerivalData = [];
        for (let i = 0; i < response.data.length; i++) {
          this.SerivalData.push({
            key: response.data[i].id,
            label: response.data[i].serialNumber,
            disabled: response.data[i].status,
          });
        }
        this.dialogFormVisible = true;

        // 回显调拨数据
        if (
          this.TransferGoodsForm.transferGoodsList[this.tempProductIndex]
            .transferGoods != null ||
          this.TransferGoodsForm.transferGoodsList[this.tempProductIndex]
            .transferGoods != undefined
        ) {
          this.TransferGoodsData =
            this.TransferGoodsForm.transferGoodsList[
              this.tempProductIndex
            ].transferGoods;
        }
      });
    },

    // 穿梭框所搜
    filterMethod(query, item) {
      if (query === "") return true;
      return item.label.indexOf(query) >= 0;
    },

    // 取消调拨商品
    colseTransferGoods() {
      this.tempProductIndex = "";
      this.SerivalData = [];
      this.transferGoodsList = { TransferGoodsData: [] };
      this.dialogFormVisible = false;
    },

    // 确认调拨商品
    saveTransferGoods() {
      // 将调拨的商品添加到调拨数据中

      this.TransferGoodsForm.transferGoodsList[
        this.tempProductIndex
      ].transferGoods = this.TransferGoodsData;

      // 关闭对话框
      this.dialogFormVisible = false;
    },

    // 获取调拨商品的数量
    getTransferNum(transferGoods) {
      if (transferGoods != null || transferGoods != undefined) {
        return transferGoods.length + "";
      } else {
        return "";
      }
    },

    // 取消库存调拨
    colseTransfer() {
      // 清除所有数据
      (this.SerivalData = []),
        (this.TransferGoodsData = []),
        (this.transferLoading = false),
        // 临时存储需要调拨的商品信息Id
        (this.tempProductIndex = ""),
        (this.TransferGoodsForm = {
          transferGoodsList: [],
        });
      this.$refs["transferGoodsRef"].resetFields();
      if (
        this.$refs.multipleTable != null ||
        this.$refs.multipleTabl != undefined
      ) {
        this.$refs.multipleTable.clearSelection();
      }
    },

    // 库存调拨
    TransferGoods() {
      // 表单验证
      // transferGoodsRef
      this.$refs["transferGoodsRef"].validate((valid) => {
        if (valid) {
          // 处理需要传递的数据 {调出仓库，调入仓库，备足，inventoryIds：[]}
          var sendData = {
            outWarehouseId: this.TransferGoodsForm.outWarehouseId,
            saveWarehouseId: this.TransferGoodsForm.saveWarehouseId,
            remark: this.TransferGoodsForm.remark,
            inventorys: [],
          };

          for (const data of this.TransferGoodsForm.transferGoodsList) {
            var goodsName = data.goodsName;
            for (const goods of data.transferGoods) {
              sendData.inventorys.push({
                inventoryId: goods,
                goodsName: goodsName,
              });
            }
          }

          if (sendData.inventorys.length > 0) {
            // 库存调拨
            transferRecordApi.transferGoods(sendData).then((response) => {
              this.$message({
                message: response.message,
                type: "success",
              });

              this.$refs.multipleTable.clearSelection();
              // 刷新
              this.getTransferTable();
            });
            this.CreateTransferVisible = false;
          } else {
            this.$message({
              message: "请选择库存",
              type: "warning",
            });
          }
        } else {
          this.$message({
            message: "表单验证不通过",
            type: "warning",
          });
          return false;
        }
      });
    },
    getTransNumTitle(row) {
      if (row.remark == null || row.remark == undefined) {
        return "备注：";
      }
      return "备注：" + row.remark;
    },

    getProductTransferNum(transferId) {
      var temp = [];
      for (const data of this.AllTransferGoodsNum) {
        if (data.transferId == transferId) {
          temp.push(data);
        }
      }

      var d = [];
      // 遍历列表中的每个 JSON 对象
      temp.forEach((obj) => {
        // 初始化一个空字符串来存储 key: value 格式的输出
        var output = "";
        // 遍历对象的每个属性
        Object.keys(obj).forEach((key) => {
          // 将 key 和 value 格式化成所需的字符串并添加到输出中

          if (key != "transferId") {
            d.push(`${key}: ${obj[key]}台`);
          }
        });
      });
      return d;
    },

    // 调拨数量求和
    addTransNum(transferId) {
      var temp = [];
      for (const data of this.AllTransferGoodsNum) {
        if (data.transferId == transferId) {
          temp.push(data);
        }
      }
      var sum = 0;
      // 遍历列表中的每个 JSON 对象
      temp.forEach((obj) => {
        // 初始化一个空字符串来存储 key: value 格式的输出
        var output = "";
        // 遍历对象的每个属性
        Object.keys(obj).forEach((key) => {
          // 将 key 和 value 格式化成所需的字符串并添加到输出中
          if (key != "transferId") {
            sum += obj[key];
          }
        });
      });

      return sum;
    },

    deleteTransferById(row) {
      this.$confirm(`确定要永久删除该记录-${row.transferId}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          transferRecordApi
            .deleteTransferById(row.transferId)
            .then((response) => {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.getTransferTable();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 打开调拨详情对话框
    openTransferInfoUi(transferId) {
      this.dialogFormVisibleInfo = true;
      this.getInfoList(transferId);
    },

    // 获取调拨详情
    getInfoList(transferId) {
      this.transferInfoLoading = true;
      transferRecordApi.getInfoList(transferId).then((response) => {
        this.transferInfoList = response.data;

        this.transferInfoLoading = false;
      });
    },
  },

  created() {
    this.getTransferTable();
  },
};
</script>

<style scoped></style>
